package com.parser.csvparser.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.text.csv.*;
import cn.hutool.core.util.CharsetUtil;

import java.util.List;

public class Parse01 {
    public static void main(String[] args) {
        //写入
        writeCsv("/Users/a123456/Downloads/test.csv");
        //解析
        parse("/Users/a123456/Downloads/test.csv");

    }
    public static void parse(String filePath) {
        CsvReadConfig config = CsvReadConfig.defaultConfig();
        config.setContainsHeader(true); // 👈 Enable header parsing

        CsvReader reader = CsvUtil.getReader(config);
        //从文件中读取CSV数据
        CsvData data = reader.read(FileUtil.file(filePath));
        List<CsvRow> rows = data.getRows();
        //遍历行
        for (CsvRow csvRow : rows) {
            Console.log(csvRow.getByName("A1"));
            //getRawList返回一个List列表，列表的每一项为CSV中的一个单元格（既逗号分隔部分）
            //            Console.log(csvRow.getRawList());
        }
    }

    public static void writeCsv(String filePath){
        //指定路径和编码
        CsvWriter writer = CsvUtil.getWriter("/Users/a123456/Downloads/test.csv", CharsetUtil.CHARSET_UTF_8);
        //按行写出
        writer.writeHeaderLine("A1","A2","A3").write(
                new String[] {"a1", "b1", "c1"},
                new String[] {"a2", "b2", "c2"},
                new String[] {"a3", "b3", "c3"}
        );

    }
}
